<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { PictureOutlined, PlusOutlined, FireOutlined } from '@ant-design/icons-vue'
import { useWallet } from '../../../composables/useWallet'

const {
  isConnected,
  isReady,
  currentAccount,
  getContract,
} = useWallet()

// NFT 表单
const nftForm = ref({
  familyId: '',
  tokenId: '',
  name: '',
  description: '',
  imageUrl: '',
  attributes: [] as { trait_type: string; value: string }[],
})

// NFT 列表
const nftList = ref<any[]>([])

// 加载状态
const isMinting = ref(false)
const isLoadingNFTs = ref(false)

// 模态框
const mintModalVisible = ref(false)

/**
 * 铸造 NFT
 */
async function mintNFT() {
  if (!isReady.value) {
    message.error('请先连接钱包')
    return
  }

  if (!nftForm.value.familyId || !nftForm.value.name) {
    message.error('请填写完整信息')
    return
  }

  isMinting.value = true

  try {
    console.log('🎨 铸造 NFT...')
    
    // 构建 tokenURI (metadata)
    const metadata = {
      name: nftForm.value.name,
      description: nftForm.value.description,
      image: nftForm.value.imageUrl,
      attributes: nftForm.value.attributes,
    }
    
    const tokenURI = `data:application/json;base64,${btoa(JSON.stringify(metadata))}`
    
    // 调用后端 API 铸造 NFT
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'}/blockchain/nft/mint`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        recipient: currentAccount.value,
        familyId: parseInt(nftForm.value.familyId),
        nftType: 0,  // 默认类型
        name: nftForm.value.name,
        description: nftForm.value.description,
        tokenURI: tokenURI,
        isSoulbound: false  // 默认不是灵魂绑定
      })
    })
    
    const result = await response.json()
    
    if (result.code !== 200) {
      throw new Error(result.message || 'NFT 铸造失败')
    }
    
    console.log('✅ NFT 铸造成功！交易哈希:', result.data.txHash)
    
    message.success(`NFT "${nftForm.value.name}" 铸造成功！`)
    
    // 重置表单
    nftForm.value = {
      familyId: '',
      tokenId: '',
      name: '',
      description: '',
      imageUrl: '',
      attributes: [],
    }
    
    mintModalVisible.value = false
    
    // 刷新 NFT 列表
    await loadUserNFTs()
    
  } catch (error: any) {
    console.error('❌ NFT 铸造失败:', error)
    
    if (error.code === 4001) {
      message.error('用户取消了交易')
    } else {
      message.error(`铸造失败: ${error.message || '未知错误'}`)
    }
  } finally {
    isMinting.value = false
  }
}

/**
 * 加载用户的 NFT
 */
async function loadUserNFTs() {
  if (!isReady.value || !currentAccount.value) return

  isLoadingNFTs.value = true

  try {
    console.log('📋 加载 NFT 列表...')
    
    // 调用后端 API 获取用户 NFT 列表
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'}/blockchain/nft/user/${currentAccount.value}`)
    const result = await response.json()
    
    if (result.code === 200) {
      nftList.value = result.data || []
      console.log('✅ NFT 列表加载完成:', nftList.value.length)
    } else {
      throw new Error(result.message || '加载 NFT 列表失败')
    }
    
  } catch (error: any) {
    console.error('❌ 加载 NFT 列表失败:', error)
    message.error(`加载 NFT 列表失败: ${error.message || '未知错误'}`)
  } finally {
    isLoadingNFTs.value = false
  }
}

/**
 * 加载家族的 NFT
 */
async function loadFamilyNFTs(familyId: string) {
  if (!isReady.value) return

  isLoadingNFTs.value = true

  try {
    console.log('📋 加载家族 NFT 列表...')
    
    // 调用后端 API 获取家族 NFT 列表
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'}/blockchain/nft/family/${familyId}`)
    const result = await response.json()
    
    if (result.code === 200) {
      nftList.value = result.data || []
      console.log('✅ 家族 NFT 列表加载完成:', nftList.value.length)
    } else {
      throw new Error(result.message || '加载家族 NFT 列表失败')
    }
    
  } catch (error: any) {
    console.error('❌ 加载家族 NFT 列表失败:', error)
    message.error(`加载家族 NFT 列表失败: ${error.message || '未知错误'}`)
  } finally {
    isLoadingNFTs.value = false
  }
}

/**
 * 添加属性
 */
function addAttribute() {
  nftForm.value.attributes.push({
    trait_type: '',
    value: '',
  })
}

/**
 * 移除属性
 */
function removeAttribute(index: number) {
  nftForm.value.attributes.splice(index, 1)
}
</script>

<template>
  <div class="nft-mint">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h2><PictureOutlined /> NFT 铸造</h2>
        <p>铸造家族徽章和纪念 NFT</p>
      </div>
      <a-space>
        <a-button
          v-if="isConnected"
          @click="loadUserNFTs"
          :loading="isLoadingNFTs"
        >
          刷新列表
        </a-button>
        <a-button
          v-if="isConnected"
          type="primary"
          size="large"
          @click="mintModalVisible = true"
        >
          <FireOutlined /> 铸造 NFT
        </a-button>
      </a-space>
    </div>

    <!-- 未连接钱包提示 -->
    <a-alert
      v-if="!isConnected"
      type="warning"
      message="请先连接钱包"
      description="您需要连接 MetaMask 钱包才能铸造和查看 NFT"
      show-icon
      style="margin-bottom: 24px"
    />

    <!-- NFT 列表 -->
    <a-card v-else title="我的 NFT" style="margin-top: 24px">
      <a-spin :spinning="isLoadingNFTs" tip="加载中...">
        <a-empty
          v-if="nftList.length === 0"
          description="您还没有 NFT"
        >
          <a-button type="primary" @click="mintModalVisible = true">
            <FireOutlined /> 立即铸造
          </a-button>
        </a-empty>

        <a-row v-else :gutter="[16, 16]">
          <a-col
            v-for="nft in nftList"
            :key="nft.tokenId"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
          >
            <a-card hoverable class="nft-card">
              <div class="nft-image">
                <img
                  v-if="nft.image"
                  :src="nft.image"
                  :alt="nft.name"
                />
                <div v-else class="nft-placeholder">
                  <PictureOutlined style="font-size: 48px; color: #ccc" />
                </div>
              </div>
              
              <div class="nft-info">
                <h3>{{ nft.name || `Token #${nft.tokenId}` }}</h3>
                <p>{{ nft.description }}</p>
                
                <div v-if="nft.attributes && nft.attributes.length > 0" class="nft-attributes">
                  <a-tag
                    v-for="(attr, index) in nft.attributes"
                    :key="index"
                    color="blue"
                  >
                    {{ attr.trait_type }}: {{ attr.value }}
                  </a-tag>
                </div>
                
                <div class="nft-footer">
                  <a-tag color="green">Token ID: {{ nft.tokenId }}</a-tag>
                </div>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </a-spin>
    </a-card>

    <!-- 铸造 NFT 模态框 -->
    <a-modal
      v-model:open="mintModalVisible"
      title="铸造 NFT"
      :confirm-loading="isMinting"
      @ok="mintNFT"
      width="700px"
    >
      <a-form :model="nftForm" layout="vertical">
        <a-form-item label="家族 ID" required>
          <a-input
            v-model:value="nftForm.familyId"
            placeholder="请输入家族 ID (0x...)"
            size="large"
          />
        </a-form-item>

        <a-form-item label="NFT 名称" required>
          <a-input
            v-model:value="nftForm.name"
            placeholder="请输入 NFT 名称"
            size="large"
            :maxlength="50"
            show-count
          />
        </a-form-item>

        <a-form-item label="NFT 描述">
          <a-textarea
            v-model:value="nftForm.description"
            placeholder="请输入 NFT 描述"
            :rows="3"
            :maxlength="200"
            show-count
          />
        </a-form-item>

        <a-form-item label="图片 URL">
          <a-input
            v-model:value="nftForm.imageUrl"
            placeholder="https://..."
            size="large"
          />
        </a-form-item>

        <a-form-item label="属性">
          <div v-for="(attr, index) in nftForm.attributes" :key="index" style="margin-bottom: 8px">
            <a-space style="width: 100%">
              <a-input
                v-model:value="attr.trait_type"
                placeholder="属性名"
                style="width: 200px"
              />
              <a-input
                v-model:value="attr.value"
                placeholder="属性值"
                style="width: 200px"
              />
              <a-button danger @click="removeAttribute(index)">删除</a-button>
            </a-space>
          </div>
          <a-button type="dashed" block @click="addAttribute">
            <PlusOutlined /> 添加属性
          </a-button>
        </a-form-item>

        <a-alert
          type="info"
          message="NFT 信息"
          description="NFT 将铸造到您当前连接的钱包地址，并永久记录在区块链上"
          show-icon
        />
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped lang="scss">
.nft-mint {
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24px;
    margin-bottom: 24px;
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    border-radius: 12px;
    color: white;
    
    .header-content {
      h2 {
        margin: 0 0 8px;
        font-size: 28px;
        color: white;
      }
      
      p {
        margin: 0;
        font-size: 14px;
        opacity: 0.9;
      }
    }
  }
  
  .nft-card {
    height: 100%;
    
    .nft-image {
      width: 100%;
      height: 200px;
      margin-bottom: 12px;
      background: #f5f5f5;
      border-radius: 8px;
      overflow: hidden;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .nft-placeholder {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
      }
    }
    
    .nft-info {
      h3 {
        margin: 0 0 8px;
        font-size: 16px;
        font-weight: 600;
      }
      
      p {
        margin: 0 0 12px;
        font-size: 14px;
        color: #666;
      }
      
      .nft-attributes {
        margin-bottom: 12px;
        
        .ant-tag {
          margin-bottom: 4px;
        }
      }
      
      .nft-footer {
        padding-top: 12px;
        border-top: 1px solid #f0f0f0;
      }
    }
  }
}
</style>

